<template>
  <div class="pre-production-plan-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="关联项目">
          <el-input v-model="searchForm.projectName" placeholder="请输入关联项目" clearable />
        </el-form-item>
        <el-form-item label="生产计划状态">
          <el-select v-model="searchForm.status" placeholder="全部" clearable>
            <el-option label="未生成" value="未生成" />
            <el-option label="生成完毕" value="生成完毕" />
            <el-option label="部分生成" value="部分生成" />
          </el-select>
        </el-form-item>
        <el-form-item label="计划编号">
          <el-input v-model="searchForm.planCode" placeholder="请输入计划编号" clearable />
        </el-form-item>
        <el-form-item label="计划主题">
          <el-input v-model="searchForm.planName" placeholder="请输入计划主题" clearable />
        </el-form-item>
        <el-form-item label="采购单据类型">
          <el-select v-model="searchForm.sourceType" placeholder="请选择单据类型" clearable>
            <el-option label="新增维修处理" value="新增维修处理" />
            <el-option label="无来源" value="无来源" />
            <el-option label="新增销售合同" value="新增销售合同" />
            <el-option label="维修单添加" value="维修单添加" />
            <el-option label="合同添加" value="合同添加" />
          </el-select>
        </el-form-item>
        <el-form-item label="添加人员">
          <el-input v-model="searchForm.creator" placeholder="请选择添加人员" clearable>
            <template #suffix>
              <el-icon class="el-input__icon" @click="handleUserSelect">
                <Search />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="添加日期">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <div class="operation-bar">
      <el-button-group>
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <el-button type="primary" @click="handleEdit" :disabled="!selectedRow">修改</el-button>
        <el-button type="danger" @click="handleDelete" :disabled="!selectedRow">删除</el-button>
      </el-button-group>
      <el-button-group>
        <el-button type="success" @click="handleReturn" :disabled="!selectedRow">返回</el-button>
        <el-button @click="handleImport">导入</el-button>
        <el-button @click="handleExport">导出</el-button>
      </el-button-group>
    </div>

    <!-- 表格区域 -->
    <el-card>
      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        border
        highlight-current-row
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="planCode" label="预生产计划编号" min-width="140" />
        <el-table-column prop="planName" label="预生产计划主题" min-width="150" show-overflow-tooltip />
        <el-table-column prop="sourceType" label="采购单据类型" min-width="120" />
        <el-table-column prop="sourceDocument" label="采购单据" min-width="180" show-overflow-tooltip />
        <el-table-column prop="projectName" label="关联项目" min-width="120" show-overflow-tooltip />
        <el-table-column prop="status" label="预生产计划状态" min-width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="planQuantity" label="本次预生产计划数量" min-width="150" />
        <el-table-column prop="generatedQuantity" label="已生成生产计划数量" min-width="150" />
        <el-table-column label="操作" fixed="right" min-width="180">
          <template #default="{ row }">
            <el-button-group>
              <el-button link type="primary" @click="handleViewDetail(row)">详情</el-button>
              <el-button link type="primary" @click="handleGeneratePlan(row)">生成生产计划</el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增预生产计划' : '编辑预生产计划'"
      width="60%"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="计划主题" prop="planName">
          <el-input v-model="form.planName" placeholder="请输入计划主题" />
        </el-form-item>
        <el-form-item label="采购单据类型" prop="sourceType">
          <el-select v-model="form.sourceType" placeholder="请选择单据类型" style="width: 100%">
            <el-option label="新增维修处理" value="新增维修处理" />
            <el-option label="无来源" value="无来源" />
            <el-option label="新增销售合同" value="新增销售合同" />
            <el-option label="维修单添加" value="维修单添加" />
            <el-option label="合同添加" value="合同添加" />
          </el-select>
        </el-form-item>
        <el-form-item label="采购单据" prop="sourceDocument" v-if="form.sourceType !== '无来源'">
          <el-input
            v-model="form.sourceDocument"
            placeholder="请选择采购单据"
            @click="handleDocumentSelect"
            readonly
          >
            <template #suffix>
              <el-icon class="el-input__icon">
                <Search />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="关联项目" prop="projectName">
          <el-select
            v-model="form.projectName"
            filterable
            remote
            placeholder="请输入关联项目"
            :remote-method="searchProjects"
            :loading="projectLoading"
            style="width: 100%"
          >
            <el-option
              v-for="item in projectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="计划数量" prop="planQuantity">
          <el-input-number
            v-model="form.planQuantity"
            :min="0"
            :precision="2"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="form.remark"
            type="textarea"
            rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="导入预生产计划"
      width="400px"
    >
      <el-upload
        class="upload-demo"
        action="/api/pre-production/plan/import"
        :auto-upload="false"
        :on-change="handleFileChange"
        :file-list="fileList"
        :headers="uploadHeaders"
      >
        <template #trigger>
          <el-button type="primary">选择文件</el-button>
        </template>
        <el-button
          class="ml-3"
          type="success"
          @click="submitUpload"
        >
          上传到服务器
        </el-button>
        <template #tip>
          <div class="el-upload__tip">
            只能上传 xlsx 文件，且不超过 10MB
          </div>
        </template>
      </el-upload>
    </el-dialog>

    <!-- 生成生产计划对话框 -->
    <el-dialog
      v-model="generateDialogVisible"
      title="生成生产计划"
      width="500px"
    >
      <el-form
        ref="generateFormRef"
        :model="generateForm"
        :rules="generateRules"
        label-width="120px"
      >
        <el-form-item label="生产计划主题" prop="planName">
          <el-input v-model="generateForm.planName" placeholder="请输入生产计划主题" />
        </el-form-item>
        <el-form-item label="生成数量" prop="quantity">
          <el-input-number
            v-model="generateForm.quantity"
            :min="1"
            :max="generateForm.maxQuantity"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="generateForm.remark"
            type="textarea"
            rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="generateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitGenerate">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import axios from 'axios'

// 搜索表单数据
const searchForm = reactive({
  projectName: '',
  status: '',
  planCode: '',
  planName: '',
  sourceType: '',
  creator: '',
  dateRange: []
})

// 表格数据
const loading = ref(false)
const tableData = ref([])
const selectedRows = ref([])
const selectedRow = ref(null)

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表单数据
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref()
const projectLoading = ref(false)
const projectOptions = ref([])

const form = reactive({
  planName: '',
  sourceType: '',
  sourceDocument: '',
  projectName: '',
  planQuantity: 0,
  remark: ''
})

// 表单验证规则
const rules = {
  planName: [{ required: true, message: '请输入计划主题', trigger: 'blur' }],
  sourceType: [{ required: true, message: '请选择单据类型', trigger: 'change' }],
  sourceDocument: [{ required: true, message: '请选择采购单据', trigger: 'blur' }],
  projectName: [{ required: true, message: '请选择关联项目', trigger: 'change' }],
  planQuantity: [{ required: true, message: '请输入计划数量', trigger: 'blur' }]
}

// 导入相关
const importDialogVisible = ref(false)
const fileList = ref([])
const uploadHeaders = {
  Authorization: `Bearer ${localStorage.getItem('token')}`
}

// 生成生产计划相关
const generateDialogVisible = ref(false)
const generateFormRef = ref()
const generateForm = reactive({
  planName: '',
  quantity: 1,
  maxQuantity: 0,
  remark: ''
})

const generateRules = {
  planName: [{ required: true, message: '请输入生产计划主题', trigger: 'blur' }],
  quantity: [{ required: true, message: '请输入生成数量', trigger: 'blur' }]
}

// 获取表格数据
const getTableData = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize,
      ...searchForm,
      startDate: searchForm.dateRange?.[0],
      endDate: searchForm.dateRange?.[1]
    }
    const response = await axios.get('/api/pre-production/plan/list', { params })
    tableData.value = response.data.records
    pagination.total = response.data.total
  } catch (error) {
    console.error('获取数据失败：', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索项目
const searchProjects = async (query) => {
  if (query.length < 2) return
  projectLoading.value = true
  try {
    const response = await axios.get('/api/project/search', {
      params: { keyword: query }
    })
    projectOptions.value = response.data
  } catch (error) {
    console.error('搜索项目失败：', error)
  } finally {
    projectLoading.value = false
  }
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    '未生成': 'warning',
    '生成完毕': 'success',
    '部分生成': 'primary'
  }
  return statusMap[status] || 'info'
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  getTableData()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 表格选择改变
const handleSelectionChange = (rows) => {
  selectedRows.value = rows
  selectedRow.value = rows.length === 1 ? rows[0] : null
}

// 行点击
const handleRowClick = (row) => {
  selectedRow.value = row
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  getTableData()
}

// 页码改变
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val
  getTableData()
}

// 新增
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  Object.keys(form).forEach(key => {
    form[key] = ''
  })
  form.planQuantity = 0
}

// 编辑
const handleEdit = () => {
  if (!selectedRow.value) {
    ElMessage.warning('请选择要编辑的记录')
    return
  }
  dialogType.value = 'edit'
  dialogVisible.value = true
  Object.keys(form).forEach(key => {
    form[key] = selectedRow.value[key]
  })
}

// 删除
const handleDelete = async () => {
  if (!selectedRow.value) {
    ElMessage.warning('请选择要删除的记录')
    return
  }
  try {
    await ElMessageBox.confirm('确定要删除该预生产计划吗？', '提示', {
      type: 'warning'
    })
    await axios.delete(`/api/pre-production/plan/delete/${selectedRow.value.id}`)
    ElMessage.success('删除成功')
    getTableData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败：', error)
      ElMessage.error('删除失败')
    }
  }
}

// 返回
const handleReturn = () => {
  if (!selectedRow.value) {
    ElMessage.warning('请选择要返回的记录')
    return
  }
  // 实现返回逻辑
  ElMessageBox.confirm('确定要返回该预生产计划吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await axios.post(`/api/pre-production/plan/return/${selectedRow.value.id}`)
      ElMessage.success('返回成功')
      getTableData()
    } catch (error) {
      console.error('返回失败：', error)
      ElMessage.error('返回失败')
    }
  }).catch(() => {})
}

// 打印
const handlePrint = () => {
  window.print()
}

// 查看日志
const handleRecheck = () => {
  if (!selectedRow.value) {
    ElMessage.warning('请选择要查看日志的记录')
    return
  }
  // 实现查看日志逻辑，可以打开一个新的对话框显示日志信息
  ElMessageBox.alert('这里显示选中记录的日志信息', '日志信息', {
    confirmButtonText: '确定'
  })
}

// 导入
const handleImport = () => {
  importDialogVisible.value = true
}

// 导出
const handleExport = async () => {
  try {
    const response = await axios.get('/api/pre-production/plan/export', {
      responseType: 'blob'
    })
    const url = window.URL.createObjectURL(new Blob([response.data]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', '预生产计划列表.xlsx')
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } catch (error) {
    console.error('导出失败：', error)
    ElMessage.error('导出失败')
  }
}

// 查看详情
const handleViewDetail = (row) => {
  // 实现查看详情逻辑
}

// 生成生产计划
const handleGeneratePlan = (row) => {
  generateDialogVisible.value = true
  generateForm.planName = `来自预生产计划:${row.planName}`
  generateForm.maxQuantity = row.planQuantity - row.generatedQuantity
  generateForm.quantity = generateForm.maxQuantity
}

// 提交生成生产计划
const submitGenerate = async () => {
  if (!generateFormRef.value) return
  await generateFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        await axios.post('/api/pre-production/plan/generate', generateForm)
        ElMessage.success('生成生产计划成功')
        generateDialogVisible.value = false
        getTableData()
      } catch (error) {
        console.error('生成失败：', error)
        ElMessage.error('生成失败')
      }
    }
  })
}

// 选择用户
const handleUserSelect = () => {
  // 实现选择用户逻辑
}

// 选择单据
const handleDocumentSelect = () => {
  // 实现选择单据逻辑
}

// 文件改变
const handleFileChange = (file) => {
  fileList.value = [file]
}

// 提交上传
const submitUpload = async () => {
  if (fileList.value.length === 0) {
    ElMessage.warning('请选择要上传的文件')
    return
  }
  try {
    const formData = new FormData()
    formData.append('file', fileList.value[0].raw)
    await axios.post('/api/pre-production/plan/import', formData)
    ElMessage.success('导入成功')
    importDialogVisible.value = false
    getTableData()
  } catch (error) {
    console.error('导入失败：', error)
    ElMessage.error('导入失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      try {
        const url = dialogType.value === 'add' 
          ? '/api/pre-production/plan/add'
          : '/api/pre-production/plan/update'
        await axios.post(url, form)
        ElMessage.success(dialogType.value === 'add' ? '添加成功' : '更新成功')
        dialogVisible.value = false
        getTableData()
      } catch (error) {
        console.error('提交失败：', error)
        ElMessage.error('提交失败')
      }
    }
  })
}

onMounted(() => {
  getTableData()
})
</script>

<style scoped>
.pre-production-plan-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  margin-top: 20px;
}

.upload-demo {
  text-align: center;
}

.ml-3 {
  margin-left: 12px;
}
</style>